﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RxxAdmin.Common.Seed;

public class MyContext
{
    private static MutiDBOperate connectObject => GetMainConnectionDb();
    private static string _connectionString = connectObject.Connection;
    private static DbType _dbType = (DbType)connectObject.DbType;
    public static string ConnId = connectObject.ConnId;
    private SqlSugarScope _db;
    public static MutiDBOperate GetMainConnectionDb()
    {
        var mainConnetctDb = BaseDBConfig.MutiConnectionString.allDbs.Find(x => x.ConnId == MainDb.CurrentDbConnId);
        if (BaseDBConfig.MutiConnectionString.allDbs.Count > 0)
        {
            if (mainConnetctDb == null)
            {
                mainConnetctDb = BaseDBConfig.MutiConnectionString.allDbs[0];
            }
        }
        else
        {
            throw new Exception("请确保appsettigns.json中配置连接字符串,并设置Enabled为true;");
        }

        return mainConnetctDb;
    }
    /// <summary>
    /// 连接字符串 
    /// </summary>
    public static string ConnectionString
    {
        get { return _connectionString; }
        set { _connectionString = value; }
    }
    /// <summary>
    /// 数据库类型 
    /// Blog.Core 
    /// </summary>
    public static DbType DbType
    {
        get { return _dbType; }
        set { _dbType = value; }
    }
    /// <summary>
    /// 数据连接对象 
    /// </summary>
    public SqlSugarScope Db
    {
        get { return _db; }
        private set { _db = value; }
    }
    public MyContext(ISqlSugarClient sqlSugarClient)
    {
        if (string.IsNullOrEmpty(_connectionString))
            throw new ArgumentNullException("数据库连接字符串为空");
        _db = sqlSugarClient as SqlSugarScope;
    }
    #region 实例方法
    /// <summary>
    /// 功能描述:获取数据库处理对象
    /// </summary>
    /// <returns>返回值</returns>
    public SimpleClient<T> GetEntityDB<T>() where T : class, new()
    {
        return new SimpleClient<T>(_db);
    }
    #endregion
}
